package com.cp.www.ws;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.kurento.client.KurentoClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

@Configuration
public class KurentoConfig implements WebSocketConfigurer {

	private Logger logger = LogManager.getLogger();

	@Value(value = "${kms.ws.ip:127.0.0.1}")
	private String kmsWsIp;

	@Value(value = "${kms.ws.port:8888}")
	private int kmsWsPort;

	@Bean
	public KurentoClient kurentoClient() {
		try {
			KurentoClient kurentoClient = KurentoClient.create("ws://" + kmsWsIp + ":" + kmsWsPort + "/kurento");
			logger.info("KurentoClient initialization success,The WebSocket is running on: {}:{}.", kmsWsIp, kmsWsPort);
			return kurentoClient;
		} catch (Exception e) {
			logger.error("KurentoClient initialization failed:{}!", e.getMessage());
			return null;
		}
	}

	@Bean
	public ServletServerContainerFactoryBean createServletServerContainerFactoryBean() {
		ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
		container.setMaxTextMessageBufferSize(32768);
		return container;
	}

	@Bean
	PlayHandler handler() {
		return new PlayHandler();
	}

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(handler(), "/player").setAllowedOrigins("*");// 解决跨域
	}

}
